package com.notelapierdas.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import com.notelapierdas.R;
import com.notelapierdas.data.DataGetter;
import com.notelapierdas.data.FakeWebDataGetter;
import com.notelapierdas.data.LocalDataGetter;
import com.notelapierdas.data.WebDataGetter;
import com.notelapierdas.db.DBHelper;
import com.notelapierdas.exceptions.NoDealsTodayException;
import com.notelapierdas.objects.Deal;

public class SplashActivity extends Activity{
	
	private final static int REQUEST_CODE_MAIN_ACTIVITY = 1;
	public final static String STRING_CODE_DEAL_LIST = "dealList";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);
		
		startThread();		
	}
	
	private void startThread(){		
		Thread dataThread = new Thread(){
			@Override
			public void run() {
				super.run();
				DataGetter dGetter= getDataGetter();
				ArrayList<Deal> dealList = dGetter.getDealList();
				Intent intent = new Intent(getApplicationContext(),MainActivity.class);
				Bundle bundle = new Bundle();
				bundle.putParcelableArrayList(STRING_CODE_DEAL_LIST, dealList);
				intent.putExtras(bundle);
				startActivityForResult(intent, REQUEST_CODE_MAIN_ACTIVITY);				
			}			
		};
		dataThread.start();
	}
	
	private DataGetter getDataGetter(){
		DataGetter dGetter = null;
		boolean fake = true;
		if(fake){
			dGetter = new FakeWebDataGetter();
		}else
		if(isOnline()){
			dGetter = new WebDataGetter();
		}else{
			DBHelper dbHelper = new DBHelper(this);
			try {
				dGetter = new LocalDataGetter(this, dbHelper);
			} catch (NoDealsTodayException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return dGetter;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
		case (REQUEST_CODE_MAIN_ACTIVITY):{
			finish();
			break;
		}
		}
	}
	
	private boolean isOnline() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}

	
}
